//
//  HRFollowDynamicViewController.m
//  Hear
//
//  Created by mac on 2017/5/19.
//  Copyright © 2017年 mac. All rights reserved.
// 广场

#import "HRFollowDynamicViewController.h"
#import "HRFollowDynamicViewModel.h"
#import "MJRefresh.h"
#import "HRFollowDynamicCell.h"
#import "HRFollowDynamicLayout.h"
#import "HRFollowDyanmicInfoViewController.h"
#import "HRGetLikesModel.h"
#import "HRDynamicViewController.h"
#import "HRVideoPlayerCell.h"
//#import "UIView+WebVideoCache.h"
//#import "UITableView+VideoPlay.h"
//#import "MyPlayTool.h"
#import "HRDynamicBannerHeadView.h"
#import "HRDynamicBannerModel.h"
#import "PopMenu.h"
#import "HRPostDynamicViewController.h"
#import "HRRecordAudioViewController.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "HRBannerCell.h"
#import "HRAnswerBannerViewController.h"
#import "HRFMDBDynamicNotifacationTool.h"
#import "HRDynamicMessageViewController.h"

#import "HRAudioPlayerView.h"
#import "HRSquareAudioPlayerViewModel.h"
#import "HRSquareAudioPlayerModel.h"
#import "UIImageView+EMWebCache.h"
#import "DOUAudioStreamer.h"
#import "DOUAudioVisualizer.h"
#import "HRDouAudioStreamerModel.h"
#import "Track.h"
#import "HRDynamicModel.h"

#define INITVOLUME 0.6
static int num = 0;
static int hideNum = 1;
@interface HRFollowDynamicViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (nonatomic, strong)HRFollowDynamicViewModel *viewModel;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *contentArray;
@property (nonatomic, assign)NSInteger pIndex;
@property (nonatomic, strong)HRGetLikesModel *likesModel;
@property (nonatomic, strong)HRDynamicModel *lastDynamicModel;

@property(nonatomic, assign)CGFloat offsetY_last;
@property(nonatomic, strong, nonnull)UIView *tableViewRange;
@property (nonatomic, assign)CGFloat tempOffset;
@property(nonatomic, strong)HRDynamicBannerHeadView *bannerHeadView;
@property (nonatomic, strong)PopMenu *popMenu;
@property (nonatomic, strong)UIView *messageHeadView;
@property (nonatomic, strong)UIButton *messageNumButton;


//@property(nonatomic, strong)HRCicleAnswerListViewController *answerListVC;
@property(nonatomic, strong)HRSquareAudioPlayerViewModel *squareAudioPlayerVM;
@property(nonatomic, strong)HRAudioPlayerView *audioPalyerView;
@property(nonatomic, strong)NSMutableArray *mutableSongURLArr;
@property(nonatomic, strong)NSMutableArray *mutableHeadImageArr;
@property (nonatomic, strong) DOUAudioStreamer *streamer;
@property (nonatomic, strong) Track *track;//audioTrack
@property (nonatomic, strong) NSMutableArray *modelMutableArr;
@property (nonatomic, strong) HRDynamicViewController *dynamicVC;
@property(nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL sliding;
@property(nonatomic, strong) HRSquareAudioPlayerModel *hrSquareAudioPlayerModel;
@property(nonatomic, strong) AVPlayer *player;
@property(nonatomic, assign) BOOL isPlaying;
@property(nonatomic, strong) AVAudioPlayer *audioPlayer;
@property(nonatomic, strong) HRDynamicModel *hrDynamicModel;

@end

@implementation HRFollowDynamicViewController

-(HRDynamicModel *)hrDynamicModel
{
    if (!_hrDynamicModel) {
        _hrDynamicModel = [HRDynamicModel new];
    }
    return _hrDynamicModel;
}

-(HRSquareAudioPlayerModel *) hrSquareAudioPlayerModel
{
    if (!_hrSquareAudioPlayerModel) {
        _hrSquareAudioPlayerModel = [HRSquareAudioPlayerModel new];
    }
    return _hrSquareAudioPlayerModel;
}


-(HRAudioPlayerView *)audioPalyerView
{
    if (!_audioPalyerView) {
        _audioPalyerView = [HRAudioPlayerView new];
        [self.view addSubview:_audioPalyerView];
//        _audioPalyerView.frame = CGRectMake(0, 64, kFullWidth, 59);
        [_audioPalyerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
            make.left.mas_equalTo(self.view.mas_left).offset(0);
            make.width.mas_equalTo(kFullWidth);
            make.height.mas_equalTo(54 * scaleHeight);
        }];
        
    }
    return _audioPalyerView;
}

-(HRSquareAudioPlayerViewModel *)squareAudioPlayerVM
{
    if (!_squareAudioPlayerVM) {
        _squareAudioPlayerVM = [HRSquareAudioPlayerViewModel new];
    }
    return _squareAudioPlayerVM;
}

-(NSMutableArray *)mutableSongURLArr
{
    if (!_mutableSongURLArr) {
        _mutableSongURLArr = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _mutableSongURLArr;
}

-(NSMutableArray *)modelMutableArr
{
    if (!_modelMutableArr) {
        _modelMutableArr = [[NSMutableArray alloc] initWithCapacity:1];
        
    }
    return _modelMutableArr;
}

-(NSMutableArray *)mutableHeadImageArr
{
    if (!_mutableHeadImageArr) {
        _mutableHeadImageArr = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _mutableHeadImageArr;
}

#pragma mark - Get and Set
- (UIView *)messageHeadView{
    if (_messageHeadView == nil) {
        _messageHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
        UIButton *messageNumButton = [UIButton buttonWithType:0];
        messageNumButton.frame = CGRectMake((_messageHeadView.width-125)/2, (_messageHeadView.height-38)/2, 125, 38);
        messageNumButton.titleLabel.font = CustomUIFont(14);
        [_messageHeadView addSubview:(self.messageNumButton=messageNumButton)];
        [messageNumButton addTarget:self action:@selector(messageNumButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [messageNumButton setBackgroundImage:[UIImage imageNamed:@"动态提示"] forState:0];
    }
    return _messageHeadView;
}

- (HRDynamicBannerHeadView *)bannerHeadView{
    if (_bannerHeadView == nil) {
        _bannerHeadView = [[HRDynamicBannerHeadView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth, 105)];
    }
    return _bannerHeadView;
}



-(HRGetLikesModel *)likesModel{
    if (_likesModel == nil){
        _likesModel = [HRGetLikesModel new];
    }
    return _likesModel;
}
-(HRFollowDynamicViewModel *)viewModel{
    if (_viewModel == nil){
        _viewModel = [HRFollowDynamicViewModel new];
    }
    return _viewModel;
}

- (void)messageNumButtonClick{
    [self.tableView.tableHeaderView removeFromSuperview];
    self.tableView.tableHeaderView = nil;
    
    HRDynamicMessageViewController *VC = [HRDynamicMessageViewController new];
    VC.isFromCircle = YES;
    VC.title = @"点滴推送";
    VC.pushTypeArray = @[@"1",@"2"];
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    self.title = @"广场";
    self.view.backgroundColor = [UIColor whiteColor];
//    [self insertLineInScreenCenter];

    self.contentArray = [NSMutableArray array];
    
   
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;

//    广场接口
    [self getFollowDynamicList];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMyDynaminclistNotifi) name:@"reloadMyDynaminclist" object:nil];
    

    
    if (self.dynamicType == TagListDynaimc)
    {
//        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        backBtn.frame = CGRectMake(0, 0, 30, 30);
//        [backBtn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//        UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
//        self.navigationItem.leftBarButtonItem = backBtn;
        self.tableView.top = kTopHeight;
        self.tableView.height -= kTopHeight;
    }
    else
    {
        self.tableView.top = kTopHeight + 59 * scaleHeight;
        self.tableView.height -= kTopHeight+59 * scaleHeight;
        UIButton *leftButton = [UIButton buttonWithType:0];
        leftButton.frame = CGRectMake(10, kStatusBarHeight, 40, 40);
        [leftButton setImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(openPlayerView) forControlEvents:UIControlEventTouchUpInside];
        self.leftButton = leftButton;
        NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:1];
        for (int i = 1; i < 4; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
            [imgArray addObject:image];
        }
        leftButton.imageView.animationImages = imgArray;
        leftButton.imageView.animationDuration = 0.7;
        //    [self.navView addSubview:leftButton];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.navigationItem.leftBarButtonItem = leftItem;
        //     打开播放界面
        [self openPlayerView];
        [self getAudioPlayerData];
        [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];
    }
    UIButton *rightButton = [UIButton buttonWithType:0];
    [rightButton setImage:[UIImage imageNamed:@"发帖按钮"] forState:0];
    rightButton.size = CGSizeMake(30, 30);
    rightButton.titleLabel.font = CustomUIFont(13);
    [rightButton addTarget:self action:@selector(postDynamicClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
//    if (self.dynamicType == DiscoverDynamic){
//        self.tableView.tableHeaderView = self.bannerHeadView;
//        [self  getBannerContent];
//    }
    if (self.dynamicType == TagListDynaimc){
//        self.tableView.top = kTopHeight;
    }else{
//        self.tableView.height -= kTabBarHeight+kNavBarHeight;
    }
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
    } else {
//        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMesageNotifi) name:@"newMesageNotifi" object:nil];
    

    
}

- (void)newMesageNotifi{
    NSInteger dynamicUnreadCount= [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"1",@"2"]];
    if (dynamicUnreadCount){
        self.tableView.tableHeaderView = self.messageHeadView;
        [self.messageNumButton setTitle:[NSString stringWithFormat:@"您有%d条动态",dynamicUnreadCount] forState:0];
    }
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无动态"];
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
{
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)reloadMyDynaminclistNotifi{
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cacheTime"];
     [self getFollowDynamic:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadMyDynaminclistNotifi" object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    self.lastDynamicModel.isPlaying = NO;
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopPlayVoiceNotification" object:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self pauseSong];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.contentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (hideNum == 1) {
        hideNum = 0;
//        解决播放器加载完成后菊花消失的问题
        [MBProgressHUD hideHUDForView:WINDOW animated:YES];
    }
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    WeakSelf
    if ([layout.dynamicModel.MomentType intValue] != 6){
        HRFollowDynamicCell *cell = [HRFollowDynamicCell cellWithTableView:tableView];
        if (layout)
        {
            cell.layout = layout;
        }
        //播放语音
        cell.playMedioBlock = ^(HRDynamicModel *currentDynamicModel){
            if (currentDynamicModel || self.lastDynamicModel){
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(![currentDynamicModel.LocalId isEqualToString:self.lastDynamicModel.LocalId]){
                        weakSelf.lastDynamicModel.isPlaying = NO;
                    }
                    [weakSelf.tableView reloadData];
                    weakSelf.lastDynamicModel = currentDynamicModel;
                    [self pauseSong];
                });
            }
        };
        cell.likeButtonClickBlock = ^(BOOL isLike){
            [weakSelf getDynamicLike:isLike andDynamic:layout.dynamicModel andFromIndex:indexPath.row];
        };
        cell.clickIconBlock = ^(){
            if ([layout.dynamicModel.UserLocalId isEqualToString:USERID]) return ;
            HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
            dynamicVC.currentUserID = layout.dynamicModel.UserLocalId;
//            dynamicVC.hidesBottomBarWhenPushed = YES;
            
            [weakSelf.navigationController pushViewController:dynamicVC animated:YES];
        };
        // 点击标签
        cell.tagButtonSenderBlock = ^(){
            if(weakSelf.dynamicType == TagListDynaimc)return;
            HRFollowDynamicViewController *dynamicVC = [HRFollowDynamicViewController new];
            dynamicVC.MomentTagCode = layout.dynamicModel.MomentTagCode;
            dynamicVC.dynamicType = TagListDynaimc;
            dynamicVC.MomentTagName = layout.dynamicModel.MomentTagName;
            [weakSelf.navigationController pushViewController:dynamicVC animated:YES];
        };
        
        cell.showMoreContentButtonBlock = ^(){// 展开
            layout.isShowRealyCellHeight = !layout.isShowRealyCellHeight;
            layout.dynamicModel = layout.dynamicModel;
            [weakSelf.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        };
        //取消cell的点击状态
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }else if ([layout.dynamicModel.MomentType intValue] == 6){
        HRBannerCell *cell = [HRBannerCell cellWithTableView:tableView];
        cell.layout = layout;
        cell.answerButtonBlock = ^{
            HRAnswerBannerViewController *VC = [HRAnswerBannerViewController new];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        return cell;
    }
    return nil;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    if ([layout.dynamicModel.MomentType intValue] == 6){
        return 420;
    }else{
        return layout.cellHeight;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    if ([layout.dynamicModel.IsRecommend intValue] ==1){
        [MobClick event:@"Hearer11"];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([layout.dynamicModel.MomentType intValue] == 6){
        return;
    }
    HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
    HRFollowDynamicLayout *detailLayout = [HRFollowDynamicLayout new];
    detailLayout.style = HRFollowLayoutStyleDetail;
    detailLayout.dynamicModel = layout.dynamicModel;
    infoVC.layout = detailLayout;
//    infoVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:infoVC animated:YES];
    WeakSelf
    infoVC.reloadListBlock = ^(NSMutableArray *commentArr){
        if (commentArr.count){
            HRDynamicModel *dynaModel = layout.dynamicModel;
            dynaModel.comentListArray = commentArr;
            layout.dynamicModel = dynaModel;
        }
        [weakSelf.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    };
}

/**
 * Called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
 * 松手时已经静止, 只会调用scrollViewDidEndDragging
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    //if (decelerate == NO)
        // scrollView已经完全静止
        
     //   [self showTabBar];
//        [self.tableView handleScrollStop];
}

/**
 * Called on tableView is static after finger up if the user dragged and tableView is scrolling.
 * 松手时还在运动, 先调用scrollViewDidEndDragging, 再调用scrollViewDidEndDecelerating
 */
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    
//    // scrollView已经完全静止
//    [self.tableView handleScrollStop];
//}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    
//    // 处理滚动方向
//    [self handleScrollDerectionWithOffset:scrollView.contentOffset.y];
//    
//    // Handle cyclic utilization
//    // 处理循环利用
//    [self.tableView handleQuickScroll];
//}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (self.dynamicType != TagListDynaimc){
//        if (self.tempOffset > scrollView.contentOffset.y){
//            if (self.tabBarController.tabBar.isHidden){
//                [self showTabBar];
//            }
//        }
//        self.tempOffset = scrollView.contentOffset.y;
//    }
    
}

- (void)hideTabBar{
    WeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tabFrame = self.tabBarController.tabBar.frame;
        tabFrame.origin.y = [[UIScreen mainScreen] bounds].size.height;
        self.tabBarController.tabBar.frame = tabFrame;
    } completion:^(BOOL finished) {
        weakSelf.tabBarController.tabBar.hidden = YES;;
    }];

}

- (void)showTabBar{
    WeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tabFrame = self.tabBarController.tabBar.frame;
        tabFrame.origin.y = kFullHeight-49;
        self.tabBarController.tabBar.frame = tabFrame;
    } completion:^(BOOL finished) {
        weakSelf.tabBarController.tabBar.hidden = NO;
        
//        DDLog(@"11111111111111111=======offset======%f tempOffset=======%f",offset,self.tempOffset);
        
    }];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    if(_dynamicType != TagListDynaimc){
//        [self hideTabBar];
//    }
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    if(_dynamicType != TagListDynaimc){
//        [self showTabBar];
//    }
}



//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    self.offsetY_last = scrollView.contentOffset.y;
//}

//-(void)handleScrollDerectionWithOffset:(CGFloat)offsetY{
//    self.tableView.currentDerection = (offsetY-self.offsetY_last>0) ? JPVideoPlayerDemoScrollDerectionUp : JPVideoPlayerDemoScrollDerectionDown;
//    self.offsetY_last = offsetY;
//}


- (void)getFollowDynamicList{
    self.pIndex = 0;
    [self getFollowDynamic:YES];

    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getFollowDynamic:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getFollowDynamic:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}

- (void)getFollowDynamic:(BOOL)isHead{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"CurrentUserLocalId"] = USERID;
    paramDict[@"PageSize"] = @"10";
    paramDict[@"PageIndex"] = [NSString stringWithFormat:@"%ld",(long)self.pIndex];
    paramDict[@"MomentTagCode"] = @"0";
    NSString *url = @"";
    if (self.dynamicType == DiscoverDynamic){
        url = @"MomentsInfo/Get_GetMomentsMyMoments";
    }else if (self.dynamicType == HotDynamic){
        url = @"MomentsInfo/Get_GetMomentsRecommend";
    }else if (self.dynamicType == FollowDynaimc){
        url = @"MomentsInfo/Get_GetMomentsMyMoments";
    }else if (self.dynamicType == TagListDynaimc){
        url = @"MomentsInfo/Get_GetMomentsRecommend";
        paramDict[@"MomentTagCode"] = self.MomentTagCode;
    }
    
    WeakSelf
    [self.viewModel getFollowDynamicList:paramDict andUrl:url resultArray:^(NSArray *resultArr) {
        
        if (resultArr){
            if (isHead){
                [weakSelf.contentArray removeAllObjects];
            }
            [weakSelf.contentArray addObjectsFromArray:resultArr];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                
                if (weakSelf.contentArray.count < 10){
                    weakSelf.tableView.mj_footer.hidden = YES;
                }else{
                    weakSelf.tableView.mj_footer.hidden = NO;
                }

            });
        }
        
        
    }];
}

#pragma 点赞
- (void)getDynamicLike:(BOOL)isLike andDynamic:(HRDynamicModel *)dynamicModel andFromIndex:(NSUInteger)index{
    
    WeakSelf
    
    if (isLike){
        [weakSelf.likesModel getLikeRequest:@{@"MomentLocalId":dynamicModel.LocalId,@"LocalId":dynamicModel.LocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} isSeccess:^(BOOL isSeccess) {
            if(isSeccess){
                dynamicModel.LikeCount = dynamicModel.LikeCount+1;
                dynamicModel.IsLike = @"1";
//                [weakSelf.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
        //        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
        //
        //        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        //
        //        });
        
    }else{
        [weakSelf.likesModel getDeletLikeRequest:@{@"MomentLocalId":dynamicModel.LocalId,@"UserLocalId":USERID} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                if (dynamicModel.LikeCount){
                    dynamicModel.LikeCount = dynamicModel.LikeCount-1;
                }
                dynamicModel.IsLike = @"0";
//                [weakSelf.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];

            }
        }];
        //        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
        //
        //        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        //            
        //        });
    }
}
- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

-(void)insertLineInScreenCenter{
    [[UIApplication sharedApplication].keyWindow insertSubview:self.tableViewRange aboveSubview:self.tableView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.dynamicType == TagListDynaimc){
//        self.hidesBottomBarWhenPushed = YES;
//        self.edgesForExtendedLayout = UIRectEdgeBottom;
        [self hideTabBar];
        self.title = self.MomentTagName;

    }else{
        [self newMesageNotifi];
    }
    if ([[NSUserDefaults standardUserDefaults] integerForKey:@"num"]) {
        num = [[NSUserDefaults standardUserDefaults] integerForKey:@"num"];
    }
    
}

- (void)getBannerContent{
    WeakSelf
    YTKApi *api = [YTKApi apiGetWithUrl:@"App/Get_GetBanners" para:nil];
    [api getSuccessToken:^() {
        [api setRequestSerializerType:YTKRequestSerializerTypeHTTP];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            weakSelf.bannerHeadView.bannerArray = [NSArray modelArrayWithClass:[HRDynamicBannerModel class] json:dict[@"BodyContent"]];


            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}

- (void)postDynamicClick{
    [self showMenu];

}

- (void)showMenu{
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:3];
    
    MenuItem *menuItem = [MenuItem itemWithTitle:@"图文动态" iconName:@"广场悬浮_心情_触摸_I"];
    [items addObject:menuItem];
    
    menuItem = [MenuItem itemWithTitle:@"语音动态" iconName:@"广场悬浮_语音_触摸_I"];
    [items addObject:menuItem];
    
    
    //    menuItem = [MenuItem itemWithTitle:@"视频动态" iconName:@"广场悬浮_语音_触摸_I"];
    //
    //    [items addObject:menuItem];
    
    
    if (!_popMenu) {
        _popMenu = [[PopMenu alloc] initWithFrame:self.view.bounds items:items];
        _popMenu.menuAnimationType = kPopMenuAnimationTypeNetEase;
        _popMenu.perRowItemCount = 2;
    }
    if (_popMenu.isShowed) {
        return;
    }
    WeakSelf
    _popMenu.didSelectedItemCompletion = ^(MenuItem *selectedItem) {
        if ([selectedItem.title isEqualToString:@"图文动态"]){
            HRPostDynamicViewController *postDynamicVC = [HRPostDynamicViewController new];
            postDynamicVC.MomentTagCode = weakSelf.MomentTagCode;
            postDynamicVC.MomentTagName = weakSelf.MomentTagName;
            postDynamicVC.clickReloadBlock = ^(){
//                            [weakSelf getFollowDynamic:YES];
            };
            
            [weakSelf.navigationController pushViewController:postDynamicVC animated:YES];
        }else if ([selectedItem.title isEqualToString:@"语音动态"]){
            HRRecordAudioViewController *audioVC = [HRRecordAudioViewController new];
            
            audioVC.MomentTagCode = weakSelf.MomentTagCode;
            audioVC.MomentTagName = weakSelf.MomentTagName;
            [weakSelf.navigationController pushViewController:audioVC animated:YES];
        }else if ([selectedItem.title isEqualToString:@"视频动态"]){
            //            QupaiSDK *sdk = [QupaiSDK shared];
            //            [sdk setDelegte:(id<QupaiSDKDelegate>)self];
            //            sdk.enableMoreMusic = NO;
            //            sdk.thumbnailCompressionQuality = 1;
            //            sdk.enableVideoEffect=NO;
            //            /* 基本设置 */
            //            UIViewController *recordController = [sdk createRecordViewControllerWithMinDuration:1
            //                                                                                    maxDuration:300
            //                                                                                        bitRate:2000*1000];
            //            recordController.hidesBottomBarWhenPushed = YES;
            //            UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:recordController];
            //            navigation.navigationBarHidden = YES;
            //            [self presentViewController:navigation animated:YES completion:nil];
            
        }
    };
    
    [_popMenu showMenuAtView:WINDOW];
}

#pragma mark  -----   打开播放器界面
-(void)openPlayerView
{
//    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(self).offset(0);
//        make.width.mas_equalTo(kFullWidth);
//        make.top.mas_equalTo(self).offset(59);
//        make
//    }];
    
    [self audioPalyerView];
    _audioPalyerView.hidden = NO;
    //    [_audioPalyerView.playBtn addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
     [_audioPalyerView.hideBtn addTarget:self action:@selector(hideView) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.playBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [_audioPalyerView.nextBtn addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [_audioPalyerView.slider addTarget:self action:@selector(volumeslidervaluechange:) forControlEvents:UIControlEventValueChanged];
    [_audioPalyerView.slider addTarget:self action:@selector(_actionSliderProgress:) forControlEvents:UIControlEventValueChanged];
    //    [_audioPalyerView.slider addTarget:self action:@selector(durationSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];
    [_audioPalyerView.userHeadBtn addTarget:self action:@selector(enterCurrentInfo) forControlEvents:UIControlEventTouchUpInside];
    [self modelMutableArr];
    [self hrSquareAudioPlayerModel];
    
    self.isPlaying = NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.02
                                                  target:self
                                                selector:@selector(updateProgress)
                                                userInfo:nil
                                                 repeats:YES];
}

#pragma mark ------ audioPlayer请求数据
-(void)getAudioPlayerData
{
    _track = [[Track alloc] init];
    
    NSMutableDictionary *audioPlayerDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [audioPlayerDic setObject:@"50000" forKey:@"PageSize"];
    [audioPlayerDic setObject:@"0" forKey:@"PageIndex"];
    [audioPlayerDic setObject:USERID forKey:@"CurrentUserLocalId"];
    NSString *url = @"SoundInfo/Get_GetSoundRecommend";
    [self.squareAudioPlayerVM getSqureAudioPlayerData:audioPlayerDic andUrl:url resultArray:^(NSMutableArray *resultArray) {
        _modelMutableArr = resultArray;
        for (HRSquareAudioPlayerModel *model in resultArray) {
            [self.mutableHeadImageArr addObject:model.UserPictureName];
            [self.mutableSongURLArr addObject:model.SoundUrl];
        }
        
        //         [self createPlayer];
        [self configSonginfo];
    }];
}

#pragma mark - set进度条
-(void)updateProgress{
    //专辑图片旋转
    
    CMTime currentTime = [self.player currentTime];
    Float64 currentPlaybackTime = CMTimeGetSeconds(currentTime);
    CMTime audioDuration = self.player.currentItem.duration;
    Float64 durationTime = CMTimeGetSeconds(audioDuration);
    //    循环播放
    //    if (currentPlaybackTime == durationTime) {
    //        [self nextBtnClick:nil];
    //    }
    
    //    if ((int)currentPlaybackTime == (int)durationTime) {
    //        [self nextBtnClick:nil];
    //    }
    
    int currentTimeMinutes = (unsigned)currentPlaybackTime/60;
    int currentTimeSeconds = (unsigned)currentPlaybackTime%60;
    
    NSMutableString *currentTimeString;
    if (currentTimeSeconds < 10) {
        currentTimeString = [NSMutableString stringWithFormat:@"%d:0%d",currentTimeMinutes,currentTimeSeconds];
    }
    else{
        currentTimeString = [NSMutableString stringWithFormat:@"%d:%d",currentTimeMinutes,currentTimeSeconds];
    }
    
    //    _audioPalyerView.progress.progress = currentPlaybackTime/[_hrSquareAudioPlayerModel.SoundLength intValue];
    //    _audioPalyerView.progress.progress = currentPlaybackTime/durationTime;
    float total = CMTimeGetSeconds(self.player.currentItem.duration);
    _audioPalyerView.slider.value = currentPlaybackTime / total;
    
}
#pragma mark - 交互
- (void)volumeslidervaluechange:(UISlider *)sender {
    _player.volume = sender.value;
}

-(void)enterCurrentInfo
{
    WeakSelf

    HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
    infoVC.dynamicID = _hrSquareAudioPlayerModel.LocalId;
    [self.navigationController pushViewController:infoVC animated:YES];
}

- (void)myBtnAction:(UIButton *)sender {
    if (self.isPlaying) {
        [self pauseSong];
    } else {
        [self playSong];
    }
}

- (void)nextBtnClick:(UIButton *)sender {
    ++num;
    if (num >= _mutableSongURLArr.count) {
        num = 0;
    }
    [[NSUserDefaults standardUserDefaults] setInteger:num forKey:@"num"];
    [self configSonginfo];
    [self playSong];
}


#pragma mark --- 配置播放器信息
-(void)configSonginfo
{
    if (num >= _modelMutableArr.count) return;
    _hrSquareAudioPlayerModel = _modelMutableArr[num];
    NSURL *url = [NSURL URLWithString:_hrSquareAudioPlayerModel.SoundUrl];
    AVPlayerItem *songItem = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [[AVPlayer alloc] initWithPlayerItem:songItem];
    self.player.volume = INITVOLUME ;
    [_audioPalyerView setValue:_hrSquareAudioPlayerModel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
}

- (void)playSong{
    [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
    [self.timer setFireDate:[NSDate distantPast]];
    self.isPlaying = YES;
    [self.player play];
    [self.leftButton.imageView startAnimating];
}

- (void)pauseSong {
    [_audioPalyerView.playBtn setImage:[UIImage imageNamed:@"播放键"] forState:UIControlStateNormal];
    [self.timer setFireDate:[NSDate distantFuture]];
    self.isPlaying = NO;
    [self.player pause];
    [self.leftButton.imageView stopAnimating];
}

-(void)playFinished
{
    [self nextBtnClick:nil];
}
#pragma mark ------- 用户拖动进度条，修改进度条
- (void)_actionSliderProgress:(UISlider *)sender
{
    //    self.sliding = YES;
    float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration);
    [self.player seekToTime:CMTimeMake(time, 1)];
}

-(void)hideView
{
    [_audioPalyerView setHidden:YES];
    self.tableView.top = kTopHeight;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
